#####################################################################################
#
# 使用 pyodbc 动态查询 SQL Server
#
#####################################################################################

import pyodbc

# 数据库连接信息
server = 'msdbt' 
database = 'wldbtest' 
username = 'wluser' 
password = 'wlpwd.123' 

# python操作数据库-SQLSERVER-pyodbc
# https://www.cnblogs.com/Evan-fanfan/p/12694287.html
#
# 在Windows上安装Microsoft ODBC SQL Server驱动程序
# https://docs.microsoft.com/en-us/sql/connect/odbc/windows/system-requirements-installation-and-driver-files?view=sql-server-2017#installing-microsoft-odbc-driver-for-sql-server

# 使用密码验证
#conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=' + server + ';DATABASE=' + database + ';UID=' + username + ';PWD=' + password)

# 使用window验证
conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=' + server + ';DATABASE=' + database + ';Trusted_Connection=yes')

# 获取 Cursor 对象
cursor = conn.cursor()

# 查询记录
cursor.execute('SELECT * FROM persons ORDER BY id')

# 获取所有记录
rows = cursor.fetchall()

# 循环打印记录
for row in rows:
    print(row)

# 连接用完后记得关闭以释放资源
conn.close()
